<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> Banner轮播图
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
				<el-button
				    type="primary"
				    icon="el-icon-circle-plus"
				    class="handle-del mr10"
				    @click="editAdd"
				>新增轮播图</el-button>
                <el-input v-model="selectTitle.title" placeholder="标题" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
				<el-button type="danger" @click="deleteSearch" icon="el-icon-delete-solid">清空</el-button>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
				<el-table-column label="序号" type="index" show-overflow-tooltip width="50"></el-table-column>
				<el-table-column label="轮播图" width="100">
					<template slot-scope="scope">
						<img :src="scope.row.picture" />
					</template>
				</el-table-column>
                <el-table-column prop="title" label="标题"></el-table-column>
				<el-table-column prop="position" label="轮播位置"></el-table-column>
				<el-table-column prop="starttime" label="开始时间"></el-table-column>
                <el-table-column prop="endtime" label="结束时间"></el-table-column>
                <el-table-column label="状态">
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.status===1?'success':'danger'"
                        >{{scope.row.status==1?'上架':'下架'}}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" @closed="handleExit">
            <el-form ref="form" :model="form" label-width="70px">
				<el-form-item label="标题">
				    <el-input v-model="form.title"></el-input>
				</el-form-item>
				<el-form-item label="轮播图位置">
				    <el-input v-model="form.position"></el-input>
				</el-form-item>
				<el-form-item label="轮播图">
					 <el-upload
					          list-type="picture"
					          action=""
					          accept="'image/*'"
					          :http-request="upLoad"
							  :on-remove="handleRemove"
					          :before-upload="beforeUploadFile"
					          :on-success="handleFileSuccess"
					          :auto-upload="true"
					          :file-list="imageValue"
					          :limit="1">
					          <el-button size="small" type="primary">轮播图上传<i class="el-icon-upload el-icon--right"></i>
							  </el-button>
					 </el-upload>
				</el-form-item>
				<el-form-item label="上架时间">
				     <el-date-picker
				          v-model="value1"
				          type="datetimerange"
				          range-separator="至"
				          start-placeholder="开始日期"
				          end-placeholder="结束日期"
						  value-format="yyyy-MM-dd HH:mm:ss"
						  format="yyyy-MM-dd HH:mm:ss">
				        </el-date-picker>
				</el-form-item>
				<el-form-item label="状态">
				     <el-select v-model="form.status" placeholder="状态">
					   <el-option label="上架" :value="1"></el-option>
					   <el-option label="下架" :value="0"></el-option>
					 </el-select>
				</el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleExit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
		
		<!-- 新增弹出框 -->
		<el-dialog title="新增轮播图" :visible.sync="add" width="30%" @closed="addExit">
		    <el-form ref="form" :model="form" label-width="70px">
				<el-form-item label="标题">
				    <el-input v-model="form.title"></el-input>
				</el-form-item>
				<el-form-item label="轮播图位置">
				    <el-input v-model="form.position"></el-input>
				</el-form-item>
				<el-form-item label="轮播图">
					 <el-upload
					          list-type="picture"
					          action=""
					          accept="'image/*'"
					          :http-request="upLoad"
							  :on-remove="handleRemove"
					          :before-upload="beforeUploadFile"
					          :on-success="handleFileSuccess"
					          :auto-upload="true"
					          :file-list="imageValue"
					          :limit="1">
					          <el-button size="small" type="primary">轮播图上传<i class="el-icon-upload el-icon--right"></i>
							  </el-button>
					 </el-upload>
				</el-form-item>
				<el-form-item label="上架时间">
				     <el-date-picker
				          v-model="value1"
				          type="datetimerange"
				          range-separator="至"
				          start-placeholder="开始日期"
				          end-placeholder="结束日期"
						  value-format="yyyy-MM-dd HH:mm:ss"
						  format="yyyy-MM-dd HH:mm:ss">
				        </el-date-picker>
				</el-form-item>
				<el-form-item label="状态">
				     <el-select v-model="form.status" placeholder="状态">
					   <el-option label="上架" value="1"></el-option>
					   <el-option label="下架" value="0"></el-option>
					 </el-select>
				</el-form-item>
		    </el-form>
		    <span slot="footer" class="dialog-footer">
		        <el-button @click="addExit">取 消</el-button>
		        <el-button type="primary" @click="handleFile">新 增</el-button>
		    </span>
		</el-dialog>
    </div>
</template>

<script>
import { allBanner } from '../../api/index.js';
import { cilent, put, remove} from '../../utils/alioss.js';
import { addBanner } from '../../api/index.js';
import axios from 'axios';
import qs from 'qs';
import { updateBanner } from '../../api/index.js';
import { deleteBanner } from '../../api/index.js';
import { searchTitle} from '../../api/index.js';
export default {
    name: 'basetable',
	props: {
	  handleSuccess: {
	    type: 'Function',
	    default: () => {}
	  },
	  handleError: {
	    type: 'Function',
	    default: () => {}
	  }
	},
    data() {
        return {
            query: {
                id : 1,
                pageIndex: 1,
                pageSize: 5
            },
            tableData: [],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {},
            idx: -1,
            id: -1,
			selectTitle:{
				pageIndex : 1,
				pageSize : 5
			},
			add:false,
			value1:[],
			imageUrl: '',
			imageValue:[],
			ids:[],
			oldname:'',
			newname:'',
			pictures:[],
			deletePic:[]
        };
    },
    created() {
        this.getData();
    },
    methods: {
		handleExit(index, row){
			this.form = {};
			this.getData();
			this.editVisible = false;
		},
		addExit(){
			this.form = {};
			this.add = false;
		},
		deleteSearch(){
			this.selectTitle.title = '';
			this.getData();
		},
		beforeUploadFile(file) {
			const isLt10M = file.size / 1024 / 1024 < 10;
			if (!isLt10M) {
			  this.$message.error("图片不能超过10M");
			  return false;
			}
		},
		handleFileSuccess(res, file,fileList){
			this.$message.success(`上传成功`);
		},
		upLoad (item) {  // item 是当前本地上传的这张图片
			// 随机命名
			let fileName = item.file.name ; // 当前本地上传的这张图片的名称
			this.baseurl = 'banner/img/';
			// 这里是把时间+图片名称拼接起来形成一个新的图片上传至oss，目的是区别于本地图片的名称，避免名称相同会误删，同时便于查看oss上最新上传图片的时间点
			let filePath = this.baseurl  + fileName;
			let file = item.file; // 当前本地上传的这张图片
			put(filePath, file).then(result => {  // 调oss api 上传图片
			console.log(result);
			  // 文件上传成功后，获取返回值中的文件名name，并把其放入fileList数组中，表示当前已上传的文件
			  this.form.picture = result.url;
			  this.newname = filePath;
			  this.$message.success('图片上传成功');
			  this.$emit('imageUrl',result)
			}).catch(e=>{
			  this.$message.error('图片上传失败');
			})
		},
		handleRemove (file) {  // file 当前本地已上传的这张图片
			console.log(file);
			let removeName = 'banner/img/' + file.name; // 当前本地已上传的这张图片的名称(带有时间日期)
			// let removeName = ''
			// this.fileList.forEach(function (name) { // forEach 在循环的数组中(fileList)找到oss和本地相同的文件名称
			//   if (name.match(fileName)) {
			// 	removeName = name // 给循环出匹配上文件名的name赋值，这里循环出的图片是带有时间日期
			//   }
			// })
			remove(removeName).then(result => { // 把循环出来的图片传进来，然后进行删除
			  console.log(result)
			  if (result.res.status != 204) {
				this.$message.error('图片删除失败');
			  }else{
				// this.select[this.problemNumber] = '';
				// this.paper.subjects[this.problemNumber].status = false;
				// this.answerCount -= 1;
				this.form.picture = null;
				this.$message({
				  message: '图片删除成功',
				  type: 'success'
				})
				this.$emit('imageUrl','')
			  }
			}).catch(e=>{
			  this.$message.error('图片删除失败');
			})
		},
        // 获取 easy-mock 的模拟数据
        getData() {
			allBanner(this.query).then(res => {
				console.log(res);
				this.tableData = res.t.list;
				this.pageTotal = res.t.total;
			});
        },
        // 触发搜索按钮
        handleSearch() {
			//console.log(this.selectLevel);
			// this.query = {
			// 	levelid:selectLevel,
			// 	pageIndex: 1,
			// 	pageSize:10
			// };
			// console.log(this.query);
   //          //this.$set(this.query, 'pageIndex', 1);
   //          this.getData();
			// if(this.selectLevel.levelid != undefined){
			// 	selectLevel(this.selectLevel).then(res => {
			// 		console.log(res);
			// 		this.tableData = res.t.list;
			// 		this.pageTotal = res.t.total;
			// 	})
			// };
			// if(this.selectUsername.name != undefined){
			// 	selectUsername(this.selectUsername).then(res => {
			// 		console.log(res);
			// 		this.tableData = res.t.list;
			// 		this.pageTotal = res.t.total;
			// 	})
			// }
			console.log(this.selectTitle.title);
			searchTitle(this.selectTitle).then(res => {
				this.tableData = res.t.list;
				this.pageTotal = res.t.total;
			})
        },
        // 删除操作
        handleDelete(index, row) {
			this.form = {id:row.id};
			var name = this.tableData[index].picture;
			console.log(name);
			var nameStr = name.split("com/");
			var str = nameStr[1];
			console.log(str);
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
					deleteBanner(this.form).then(res => {
						if(res.code == 200){
							remove(str).then(result => { // 把循环出来的图片传进来，然后进行删除
								console.log(result)
							});
							this.$message.success('删除成功');
							this.getData();
						}else{
							this.$message.error('删除失败');
						}
					});
                    
                })
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            for(var i = 0; i < val.length; i++){
				this.ids[i] = val[i].id;
				this.pictures[i] = val[i].picture.split("com/")[1];
			}
			this.multipleSelection = this.ids;
			this.deletePic = this.pictures;
			this.ids = [];
			this.pictures = [];
			console.log(this.deletePic);
        },
        delAllSelection() {
            // const length = this.multipleSelection.length;
            // let str = '';
            // this.delList = this.delList.concat(this.multipleSelection);
            // for (let i = 0; i < length; i++) {
            //     str += this.multipleSelection[i].name + ' ';
            // }
            // this.$message.error(`删除了${str}`);
            // this.multipleSelection = [];
			axios.post('http://localhost:8080/banner/deleteSelect', qs.stringify(
				{ids:this.multipleSelection},
				{indices:false}
			)).then(res => {
				if(res.data.code == 200){
					this.$message.success('删除成功');
					for(var i = 0; i < this.deletePic.length; i++){
						remove(this.deletePic[i]);
					}
					this.getData();
				}else{
					this.$message.error('删除失败');
				}
				this.multipleSelection = [];
			})
        },
		editAdd(){
			this.add = true;
		},
		handleFile(){
			if(this.form.picture == null){
				this.$message.error(`请选择一张图片`);
				return;
			}
			this.form.starttime = this.value1[0];
			this.form.endtime = this.value1[1];
			addBanner(this.form).then(res => {
				if(res.code == 200){
					this.add = false;
					this.$message.success(`新增成功`);
					this.getData();
				}else{
					this.add = false;
					this.$message.success(`新增失败`);
				}
			})
		},
		handleAvatarSuccess(res, file) {
			this.form.picture = URL.createObjectURL(file.raw);
			console.log(this.form);
		},
        // 编辑操作
        handleEdit(index, row) {
            // this.idx = index;
            // this.form = {id:row.id, endtime:row.endtime}
			this.oldname = row.picture;
			var name = this.oldname;
			var nameStr = name.split("com/");
			var str = nameStr[1];
			this.oldname = str;
			this.form = JSON.parse(JSON.stringify(row));
			console.log(row);
			this.value1[0] = row.starttime;
			this.value1[1] = row.endtime;
			this.form.id = row.id;
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.editVisible = false;
			if(this.oldname != this.newname && this.newname != ''){
				remove(this.oldname).then(result => { // 把循环出来的图片传进来，然后进行删除
					console.log(result)
				});
			}
			updateBanner(this.form).then(res => {
				if(res.code == 200){
					this.$message.success(`修改成功`);
					this.getData();
				}else{
					this.$message.error(`修改失败`)
				}
			})
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  img{
	  height: auto;
	  width: 100%;
  }
</style>

